package com.aw.baselib.net.callback;

import com.aw.baselib.R;
import com.aw.baselib.base.AwBaseApplication;
import com.aw.baselib.base.AwResponseBean;
import com.aw.baselib.bean.rx.EventReLoginType;
import com.aw.baselib.util.AwLog;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.functions.Consumer;

/**
 * @author : hzw
 * @date : 2021/12/10
 */
public class AwRspSubscriber<T> implements Consumer<AwResponseBean<T>> {

    public static final int UNKNOWN_CODE = -1;
    private AwRspCallback<T> mRspCallback;

    public AwRspSubscriber(AwRspCallback<T> rspCallback) {
        mRspCallback = rspCallback;
    }

    @Override
    public void accept(AwResponseBean<T> rspBean){
        if(null == mRspCallback) {
            AwLog.d("===AwRspConsumer callback is null, return");
        } else {
            if(rspBean == null) {
                AwLog.d("===AwRspConsumer callback rspBean is null");
                mRspCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_server_return_empty_data));
            } else {
                AwLog.d("===AwRspConsumer callback rspBean is normal, rspBean: " + rspBean.toString());
                if(rspBean.isTokenError()) {
                    EventBus.getDefault().postSticky(new EventReLoginType(null));
                } else if(rspBean.isSuccess()) {
                    mRspCallback.onSuccess(rspBean.getData());
                } else {
                    mRspCallback.onFailure(rspBean.getCode(), rspBean.getMsg());
                }
            }
            mRspCallback.onCompleted();
        }

    }
}
